import json

import cv2
import numpy as np
import time
from mss import mss
from PIL import Image
import pytesseract

# 读取配置文件
with open('config.json', 'r') as config_file:
    config = json.load(config_file)

# 设置 Tesseract 路径（如果没有添加到 PATH）
pytesseract.pytesseract.tesseract_cmd = config['tesseract_path']

def capture_screen_mss(left, top, width, height):
    with mss() as sct:
        monitor = {"left": left, "top": top, "width": width, "height": height}
        screenshot = np.array(sct.grab(monitor))
        return cv2.cvtColor(screenshot, cv2.COLOR_RGBA2BGR)

def detect_text(image):
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    text = pytesseract.image_to_string(pil_image, lang='chi_sim')
    print(f"识别到的文字: {text}")
    return "创建" in text

def monitor_screen(screen_config: dict):
    try:
        screen = capture_screen_mss(
            screen_config['left'],
            screen_config['top'],
            screen_config['width'],
            screen_config['height']
        )
        if detect_text(screen):
            return True
        time.sleep(0.5)
    except KeyboardInterrupt:
        print("监控已停止")
